<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios';
const utilitybillData=ref([            {
  "billid":'',
  "waterusage": '',
  "watercost": '',
  "electricityusage": '',
  "electricitycost": '',
  "totalamount": '',
  "remainingbalance": '',
  "createtime": "",
  "endtime": ""
},]);

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  utilityBillList();

}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  utilityBillList();
}
const name = ref('')


import {rechargeNewRecordService} from "@/api/recharge.js"
import {utilityInfoService,R_utilityInfoService} from "@/api/utilitybill.js"
import {ElMessage} from "element-plus";

import useUserInfoStore from "@/stores/userInfo.js"
const userInfoStore = useUserInfoStore()
const isAdmin=(userInfoStore.userInfo.usertype===1);
const utilityBillList=async ()=>{
  if(isAdmin){
    let params={
      pageNum:pageNum.value,
      pageSize:pageSize.value,
      realname:name.value,
    }
    let result=await R_utilityInfoService(params)
    utilitybillData.value=result.data.items
    total.value=result.data.total
  }else{
    let params={
      pageNum:pageNum.value,
      pageSize:pageSize.value,
    }
    let result=await utilityInfoService(params)
    utilitybillData.value=result.data.items
    total.value=result.data.total
    const dateString =  utilitybillData.value[1].createtime
    const dateObject = new Date(dateString);

    const month = dateObject.getMonth() + 1;

    console.log(month); // 输出：7
  }
}
utilityBillList();


//复用充值弹窗
// 充值对话框
const rechargeInformationVisible = ref(false)
const newRechargeRecord = ref(false)
const formLabelWidth = '80px'
const newRechargeRecordData = ref({
  paymentmethod: '',
  amount:''
});

function validateAmount(rule, value, callback) {
  if (isNaN(value)) {
    callback(new Error('充值金额必须为数字'));
  } else {
    callback();
  }
}

const rules={
  amount:[
    {required:true,message:'请填写充值金额',trigger:'blur'},
    { validator: validateAmount, trigger: 'blur' }
  ],
  paymentmethod:[
    {required:true,message:'请选择充值方式',trigger:'blur'}
  ]
}


const recharge=async()=>{
  let result = await rechargeNewRecordService(newRechargeRecordData.value)
  ElMessage.success("支付成功")
  userInfoStore.userInfo.accountbalance += Number(newRechargeRecordData.value.amount);
  rechargeInformationVisible.value = false;
}


import{utilityBillDownloadService} from "@/api/utilitybill.js"
const downloadUtilityBill=async (index,row)=>{
  const billid=row.billid;
  let result = await utilityBillDownloadService(billid)
  console.log(result)
  // 假设result.data是包含下载链接的网址
  const downloadUrl = result.data;
  // 创建一个新的<a>标签，用于下载文件
  const link = document.createElement('a');
  link.href = downloadUrl;
  // 可以设置下载的文件名
  link.download = row.billid+'utility_bill.pdf'; // 根据需要修改文件名
  // 模拟点击<a>标签来下载文件
  document.body.appendChild(link);
  link.click();
  // 下载完成后移除<a>标签
  document.body.removeChild(link);
}


</script>

<template>
  <el-container >
    <!-- 余额显示区域 -->
    <el-header>
      <el-row>
        <el-col :span="3" v-if="userInfoStore.userInfo.usertype===0">
          <p><strong>余额：{{ userInfoStore.userInfo.accountbalance }}</strong></p>
        <!-- 添加充值按钮 -->
        </el-col>
        <el-col :span="2" v-if="userInfoStore.userInfo.usertype===0">
          <el-button type="danger"  @click="rechargeInformationVisible=true;">充值</el-button>
        </el-col>
        <el-col :span="12">
        <el-form inline v-if="isAdmin">
          <el-form-item>
            <el-input v-model="name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="utilityBillList">查询</el-button>
          </el-form-item>
        </el-form>
        </el-col>
      </el-row>
    </el-header>

    <!-- 表格区域 -->
    <el-main>
      <el-table :data="utilitybillData" style="width: 100%" stripe>
        <el-table-column prop="realname" label="用户名" v-if="isAdmin"></el-table-column>
        <el-table-column prop="waterusage" label="用水量" ></el-table-column>
        <el-table-column prop="watercost" label="水费" ></el-table-column>
        <el-table-column prop="electricityusage" label="用电量" ></el-table-column>
        <el-table-column prop="electricitycost" label="电费" ></el-table-column>
        <el-table-column prop="totalamount" label="当月费用总和"></el-table-column>
        <el-table-column prop="remainingbalance" label="扣费后余额"></el-table-column>
        <el-table-column prop="createtime" label="开始时间"></el-table-column>
        <el-table-column prop="endtime" label="结束时间"></el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button size="small" type="primary" @click="downloadUtilityBill(scope.$index, scope.row)" :disabled="!scope.row.endtime">
              下载水电费账单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[ 5 , 8 ,10, 15]"
                           layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                           @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    </el-main>

    <el-dialog v-model="rechargeInformationVisible" title="填写支付信息" width="500">
      <el-form :model="newRechargeRecordData" :rules="rules">
        <el-form-item prop="amount" label="充值金额" :label-width="formLabelWidth">
          <el-input v-model="newRechargeRecordData.amount" placeholder="请填写支付金额" />
        </el-form-item>
        <el-form-item prop="paymentmethod" label="支付方式" :label-width="formLabelWidth">
          <el-select v-model="newRechargeRecordData.paymentmethod" placeholder="请选择支付方式">
            <el-option label="微信支付" value="微信支付" />
            <el-option label="支付宝支付" value="支付宝支付" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rechargeInformationVisible = false">取消支付</el-button>
          <el-button type="primary" @click="recharge">
            支付完毕
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<style scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.balance {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
.balance-info {
  flex: 1; /* 使余额信息占据剩余空间 */
  display: flex;
  align-items: center; /* 垂直居中对齐余额文本和按钮 */
}
/* 根据需要添加更多样式 */
</style>